package com.moyun.modelclass.frank;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseAdapter<V extends ViewDataBinding, M> extends RecyclerView.Adapter<BaseAdapter.ViewHolder<V>> {
    protected final List<M> mDataList = new ArrayList<>();


    public void addData(List<M> list) {
        if (list != null) {
            mDataList.addAll(list);
        }
        notifyDataSetChanged();
    }

    public List<M> getData() {
        return mDataList;
    }

    public void setData(List<M> list) {
        mDataList.clear();
        if (list != null) {
            mDataList.addAll(list);
        }
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder<V> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        try {
            Class<? extends BaseAdapter> aClass = getClass();
            Type genericSuperclass = aClass.getGenericSuperclass();
            if (genericSuperclass instanceof ParameterizedType) {
                Class type =
                        (Class) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
                Method method = type.getMethod("inflate", LayoutInflater.class, ViewGroup.class,
                        boolean.class);
                V viewBinding = (V) method.invoke(null, LayoutInflater.from(parent.getContext()),
                        parent, false);
                return new ViewHolder<V>(viewBinding);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder<V> holder, int position) {
        V binding = holder.mBinding;
        M m = mDataList.get(position);
        View itemView = holder.itemView;
        onBindData(m, binding, position, itemView);
    }

    protected void onBindData(M bean, V binding, int position, View itemView) {
        binding.setVariable(1, bean);
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    public static class ViewHolder<V extends ViewDataBinding> extends RecyclerView.ViewHolder {
        public final V mBinding;

        public ViewHolder(@NonNull V v) {
            super(v.getRoot());
            mBinding = v;
        }
    }
}
